<?php

namespace seraph_pds;

// Exit if accessed directly
if( !defined( 'ABSPATH' ) )
	exit;

// #######################################################################
// PluginOptions

class PluginOptions
{
	static private $optionsCache = NULL;

	static function Get( $ver, $name, $cbNs = '' )
	{
		$data = is_array( self::$optionsCache ) ? @self::$optionsCache[ $name ] : NULL;
		if( $data )
			return( $data );

		$data = get_option( 'seraph_pds' . '_' . $name );

		$vFrom = is_array( $data ) ? @$data[ 'v' ] : NULL;
		$data[ 'v' ] = $ver;

		{
			$funcName = $cbNs . 'OnOptRead_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$data = call_user_func( $funcName, $data, $vFrom );
		}

		self::$optionsCache[ $name ] = $data;
		return( $data );
	}

	static function Set( $ver, $name, $data, $cbNs = '' )
	{
		$data[ 'v' ] = $ver;

		// Write prepare
		{
			$funcName = $cbNs . 'OnOptWritePrep_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$data = call_user_func( $funcName, $data );
		}

		self::$optionsCache[ $name ] = $data;

		// Write data
		$dataWrite = $data;
		{
			$funcName = $cbNs . 'OnOptWrite_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$dataWrite = call_user_func( $funcName, $dataWrite );
		}

		return( update_option( 'seraph_pds' . '_' . $name, $dataWrite ) );
	}

	static function Del( $name )
	{
		unset( self::$optionsCache[ $name ] );
		delete_option( 'seraph_pds' . '_' . $name );
	}
}

// #######################################################################
// PostOptions

class PostOptions
{
	static private $optionsCache = NULL;

	static function Get( $post, $ver, $name, $cbNs = '' )
	{
		if( !$post )
			return( null );

		$postId = $post -> ID;
		$cachePath = array( $post -> post_type, $postId, $name );

		$data = Gen::GetArrField( self::$optionsCache, $cachePath );
		if( $data )
			return( $data );

		$data = get_post_meta( $postId, '_' . 'seraph_pds' . '_' . $name, true );

		$vFrom = is_array( $data ) ? @$data[ 'v' ] : NULL;
		$data[ 'v' ] = $ver;

		{
			$funcName = $cbNs . 'OnPostOptRead_' . $post -> post_type . '_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$data = call_user_func( $funcName, $data, $vFrom );
		}

		Gen::SetArrField( self::$optionsCache, $cachePath, $data );
		return( $data );
	}

	static function Set( $post, $ver, $name, $data, $cbNs = '' )
	{
		if( !$post )
			return( false );

		$data[ 'v' ] = $ver;

		// Write prepare
		{
			$funcName = $cbNs . 'OnPostOptWritePrep_' . $post -> post_type . '_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$data = call_user_func( $funcName, $data );
		}

		$postId = $post -> ID;
		$cachePath = array( $post -> post_type, $postId, $name );

		Gen::SetArrField( self::$optionsCache, $cachePath, $data );

		// Write data
		$dataWrite = $data;
		{
			$funcName = $cbNs . 'OnPostOptWrite_' . $post -> post_type . '_' . $name;
			if( Gen::DoesFuncExist( $funcName ) )
				$dataWrite = call_user_func( $funcName, $dataWrite );
		}

		return( update_post_meta( $postId, '_' . 'seraph_pds' . '_' . $name, $dataWrite ) );
	}

	static function Del( $post, $name )
	{
		if( !$post )
			return( false );

		$postId = $post -> ID;
		$cachePath = array( $post -> post_type, $postId, $name );

		Gen::SetArrField( self::$optionsCache, $cachePath, null );
		delete_post_meta( $postId, '_' . 'seraph_pds' . '_' . $name );
		return( true );
	}
}

// #######################################################################
// PluginRmtCfg

class PluginRmtCfg
{
	const STG_VER			= 1;

	static function Update( $bForce = false, $bFirstTimeOnly = false )
	{
		$data = PluginOptions::Get( self::STG_VER, 'RmtCfg', __CLASS__ . '::' );
		$curUpdTime = time();

		if( !$bForce )
		{
			if( $bFirstTimeOnly )
			{
				$lastCheckVer = @$data[ 'plgVer' ];
				if( $lastCheckVer == '1.5.1' )
					return( Gen::S_FALSE );
			}

			if( ( $curUpdTime - $data[ 'updTime' ] ) <= 3600 )
				return( Gen::S_FALSE );
		}

		$urlRemoteCfg = null;
		{
			$plgMode = constant( 'seraph_pds' . '_PLUGIN_MODE' );

			$args = array();
			$args[ 'pm' ] = $plgMode ? $plgMode : 'base';
			$args[ 'v' ] = '1.5.1';
			$args[ 'epid' ] = Gen::GetSiteId();

			$urlRemoteCfg = add_query_arg( $args, 'https://www.s-sols.com/data/products/wordpress/post-docx-source/cfg0002.json.txt' );
		}

		if( @$data[ 'mdfTime' ] )
		{
			$requestRes = wp_remote_head( $urlRemoteCfg, array( 'timeout' => 15 ) );

			$timeMdf = 0;
			$hr = self::_Update_GetResMdfTime( $requestRes, $timeMdf );
			if( $hr != Gen::S_OK )
				return( $hr );

			if( $data[ 'mdfTime' ] >= $timeMdf )
			{
				$data[ 'updTime' ] = $curUpdTime;
				$data[ 'plgVer' ] = '1.5.1';
				PluginOptions::Set( self::STG_VER, 'RmtCfg', $data, __CLASS__ . '::' );
				return( Gen::S_OK );
			}
		}

		$requestRes = wp_remote_get( $urlRemoteCfg, array( 'timeout' => 15 ) );

		$timeMdf = 0;
		$hr = self::_Update_GetResMdfTime( $requestRes, $timeMdf );
		if( $hr != Gen::S_OK )
			return( $hr );

		$data[ 'mdfTime' ] = $timeMdf;
		$data[ 'updTime' ] = $curUpdTime;
		$data[ 'plgVer' ] = '1.5.1';
		$data[ 'data' ] = json_decode( wp_remote_retrieve_body( $requestRes ), true );
		PluginOptions::Set( self::STG_VER, 'RmtCfg', $data, __CLASS__ . '::' );
		return( Gen::S_OK );
	}

	static function Get()
	{
		$data = PluginOptions::Get( self::STG_VER, 'RmtCfg', __CLASS__ . '::' );
		return( $data[ 'data' ] );
	}

	// #######################################################################

	static private function _Update_GetResMdfTime( $requestRes, &$timeMdf )
	{
		if( is_wp_error( $requestRes ) )
			return( Gen::E_FAIL );

		$httpCode = wp_remote_retrieve_response_code( $requestRes );
		if( $httpCode == 200 )
			$timeMdf = strtotime( wp_remote_retrieve_header( $requestRes, 'last-modified' ) );

		return( Gen::S_OK );
	}

	// #######################################################################

	static function OnOptRead_RmtCfg( $data, $verFrom )
	{
		if( !isset( $data[ 'data' ] ) || !is_array( $data[ 'data' ] ) )
			$data[ 'data' ] = array();
		if( !isset( $data[ 'updTime' ] ) )
			$data[ 'updTime' ] = 0;
		return( $data );
	}
}

// #######################################################################
// Plugin

class Plugin
{
	const STATE_VER			= 1;

	static function Init()
	{
		$isAdminMode = is_admin();

		if( $isAdminMode )
		{
			PluginRmtCfg::Update( false, true );
			add_action( 'admin_notices', __CLASS__ . '::' . '_on_admin_notices' );
		}

		add_filter( 'pre_set_site_transient_update_plugins',		__CLASS__ . '::' . '_on_site_transient_update_plugins', 10, 2 );

		if( $isAdminMode )
		{
			if( isset( $_GET[ self::_ActionArg() ] ) )
			{
				$act = $_GET[ self::_ActionArg() ];
				switch( $act )
				{
				case 'accept_eula':
					require_once( ABSPATH . 'wp-includes/pluggable.php' );

					self::_AcceptEula();
					wp_redirect( remove_query_arg( self::_ActionArg(), $_SERVER[ 'REQUEST_URI' ] ) );
					exit();

					break;

				case 'switch_to_ext':
					self::_AcceptEula();
					self::_SwitchTo( 'ext' );
					exit();

					break;

				case 'switch_to_full':
					self::_SwitchTo( 'full' );
					exit();

					break;

				case 'rateItDisable':
					self::_RateIt_Set( false );
					exit();

				case 'rateItPostpone':
					self::_RateIt_Set( true );
					exit();

					break;
				}
			}

			add_action( 'admin_enqueue_scripts', __CLASS__ . '::' . '_on_admin_style' );
		}

		if( !self::IsEulaAccepted() )
			return;

		// Set first time usage
		{
			$state = PluginOptions::Get( self::STATE_VER, 'State', __CLASS__ . '::' );
			if( !isset( $state[ 'firstUseTimeStamp' ] ) )
			{
				$state[ 'firstUseTimeStamp' ] = time();
				PluginOptions::Set( self::STATE_VER, 'State', $state, __CLASS__ . '::' );
			}
		}

		add_filter( 'do_parse_request',								__CLASS__ . '::' . '_on_parse_request', 0, 1 );
		add_filter( 'plugins_update_check_locales',					__CLASS__ . '::' . '_on_check_plugins_updates', 10, 1 );

		if( $isAdminMode )
		{
			call_user_func( 'seraph_pds\\OnInitAdminMode' );
		}
	}

	static private $_IsEulaAccepted = null;

	static function IsEulaAccepted()
	{
		if( self::$_IsEulaAccepted !== null )
			return( self::$_IsEulaAccepted );
		return( self::$_IsEulaAccepted = self::_IsEulaAccepted() );
	}

	static private function _IsEulaAccepted()
	{
		if( !constant( 'seraph_pds' . '_PLUGIN_MODE' ) )
			return( true );

		$state = PluginOptions::Get( self::STATE_VER, 'State', __CLASS__ . '::' );
		return( $state[ 'eulaAcceptedVer' ] == namespace\PLUGIN_EULA_VER );
	}

	static function SwitchToExt( $block = false )
	{
		$rmtCfg = PluginRmtCfg::Get();

		$dwnldUrl = Gen::GetArrField( $rmtCfg, 'Links.UrlProductDownload' );
		if( !$dwnldUrl )
			return;

		$switchBtnName = __( "Switch to Free Extended Version", 'seraph_pds' );

		$res = '';
		$res .= 'Switch to the <strong>free plugin version</strong> with ' . Ui::HtmlLink( 'extended features', Gen::GetArrField( $rmtCfg, 'Links.UrlProductInfo' ), true ) . '.';
		if( $block )
			$res .= '<br/><br/>';
		else
			$res .= ' ';
		$res .= 'The version will be downloaded and the existing one will be replaced automatically. By pressing "' . $switchBtnName . '" button you are agreeing with the ' . Ui::HtmlLink( 'End-User License Agreement', Gen::GetArrField( $rmtCfg, 'Links.UrlEula' ), true ) . '.';

		$res .= '<p><input type="button" class="button';
		if( $block )
			$res .= ' button-primary';
		$res .= '" value="' . $switchBtnName . '" style="margin-right: 0.5em;" onclick="window.location.href=\'' . add_query_arg( array( self::_ActionArg() => 'switch_to_ext' ), $_SERVER[ 'REQUEST_URI' ] ) . '\'" /></p>';
		return( $res );
	}

	static function DisplayAdminFooterRateItContent()
	{
		if( self::RateIt_ShouldShow() !== false )
			add_filter( 'admin_footer_text', __CLASS__ . '::' . '_OnFilter_AdminFooterText', 10, 1 );
	}

	const RateItContent_Msg		= 'msg';
	const RateItContent_Box		= 'box';
	const RateItContent_Str		= null;

	static function GetRateItContent( $type = self::RateItContent_Str )
	{
		$rmtCfg = PluginRmtCfg::Get();
		$res = sprintf( __( 'If you like the plugin please could you give us a %s rating.' . ( $type ? ' It really improves the plugin and helps other people.' : '' ) . ( $type == 'box' ? '<br/><br/>' : ' ' ) . 'Thank you very much in advance. We do %s.', 'seraph_pds' ), Ui::HtmlLink( '&#9733;&#9733;&#9733;&#9733;&#9733;', 'https://wordpress.org/support/plugin/' . 'seraphinite-post-docx-source' . '/reviews?rate=5#new-post', true ), Ui::HtmlLink( __( 'all of our best', 'seraph_pds' ), Gen::GetArrField( $rmtCfg, 'Links.UrlRatingAboutUs' ), true ) );
		return( $res );
	}

	static function GetAboutPluginContent()
	{
		$rmtCfg = PluginRmtCfg::Get();

		$urlProductInfo = Gen::GetArrField( $rmtCfg, 'Links.UrlProductInfo' );
		$urlAboutPluginImg = file_exists( dirname( __FILE__ ) . '/../Images/ProductLogo.Png' ) ? plugins_url( '../Images/ProductLogo.Png', __FILE__ ) : null;
		$urlAboutPluginDocs = Gen::GetArrField( $rmtCfg, 'Links.UrlProductDocs' );
		$urlAboutPluginSupport = Gen::GetArrField( $rmtCfg, 'Links.UrlProductSupport' );
		$urlEula = constant( 'seraph_pds' . '_PLUGIN_MODE' ) ? Gen::GetArrField( $rmtCfg, 'Links.UrlEula' ) : null;
		$url3rdPartySoft = file_exists( dirname( __FILE__ ) . '/../third-party-software.html' ) ? plugins_url( '../third-party-software.html', __FILE__ ) : null;

		$res = '';

		{
			$res .= '<div style="display:inline-block;width:100%;">';

			if( !empty( $urlAboutPluginImg ) )
				$res .= Ui::HtmlLink( '<img width=100 style="float:left;" src="' . $urlAboutPluginImg . '" /></p>', $urlProductInfo, true );

			$res .= '<h3 style="margin:0">Seraphinite Post .DOCX Source</h3>';
			$res .= '<div style="margin-top:0.3em"><strong>Version:</strong>&nbsp;1.5.1</div>';

			$res .= '</div>';
		}

		{
			$res .= '<p>';

			$res .= '<p style="display:inline-block;">Save a lot of your time by automatically converting from .DOCX to content with all attributes and in a batch mode as well.</p>';

			$linksPrms = array( 'noTextIfNoHref' => true, 'linkPreContent' => '<div>', 'linkAfterContent' => '</div>' );

			$res .= Ui::HtmlLink( 'Documentation', $urlAboutPluginDocs, true, $linksPrms );
			$res .= Ui::HtmlLink( 'Support', $urlAboutPluginSupport, true, $linksPrms );
			$res .= Ui::HtmlLink( 'End-User License Agreement', $urlEula, true, $linksPrms );
			$res .= Ui::HtmlLink( 'Third-Party Software', $url3rdPartySoft, true, $linksPrms );

			$res .= '</p>';
		}

		return( $res );
	}

	static function GetAboutVendorContent()
	{
		$rmtCfg = PluginRmtCfg::Get();

		$urlAboutUsLogoImg = file_exists( dirname( __FILE__ ) . '/../Images/VendorLogo.Png' ) ? plugins_url( '../Images/VendorLogo.Png', __FILE__ ) : null;
		$urlMorePlugins = Gen::GetArrField( $rmtCfg, 'Links.UrlMorePlugins' );
		$urlMoreInfo = Gen::GetArrField( $rmtCfg, 'Links.UrlMain' );

		$res = '';

		if( !empty( $urlAboutUsLogoImg ) )
		{
			$res .= '<p style="display:inline-block;width:100%;">';
			$res .= Ui::HtmlLink( '<img src="' . $urlAboutUsLogoImg . '" />', $urlMoreInfo, true );
			$res .= '</p>';
		}

		$res .= '<p>';
		$res .= 'We develop solutions for WordPress and other platforms to streamline Your business and life.';
		$res .= '<br/><br/>';
		$res .= 'Please, ' . Ui::HtmlLink( 'contact us', Gen::GetArrField( $rmtCfg, 'Links.UrlSupport' ), true ) . ' if you have any question according to our software.';
		$res .= '</p>';

		if( !empty( $urlMorePlugins ) || !empty( $urlMoreInfo ) )
			$res .= '<br/>';

		if( !empty( $urlMorePlugins ) )
			$res .= '<input style="margin-right:0.5em;" type="button" class="button" value="More plugins..." onclick="window.open( \'' . $urlMorePlugins . '\', \'_blank\' )" />';

		if( !empty( $urlMoreInfo ) )
			$res .= '<input style="margin-right:0.5em;" type="button" class="button" value="More info..." onclick="window.open( \'' . $urlMoreInfo . '\', \'_blank\' )" />';

		return( $res );
	}

	// #######################################################################
	// Data

	static function DataGet()
	{
		return( PluginOptions::Get( PLUGIN_DATA_VER, 'Data', 'seraph_pds' . '\\' ) );
	}

	static function DataSet( $data )
	{
		return( PluginOptions::Set( PLUGIN_DATA_VER, 'Data', $data, 'seraph_pds' . '\\' ) );
	}

	// #######################################################################
	// Settings

	static function SettGet()
	{
		return( PluginOptions::Get( PLUGIN_SETT_VER, 'Sett', 'seraph_pds' . '\\' ) );
	}

	static function SettSet( $data )
	{
		PluginOptions::Set( PLUGIN_SETT_VER, 'Sett', $data, 'seraph_pds' . '\\' );
		// MBI !!!! check DB write error
		return( true );
	}

	// #######################################################################

	static function PostSettGet( $post )
	{
		if( !$post )
			return( null );

		$ver = constant( 'seraph_pds' . '\\' . 'PLUGIN_' . strtoupper( $post -> post_type ) . '_SETT_VER' );
		return( PostOptions::Get( $post, $ver, 'Sett', 'seraph_pds' . '\\' ) );
	}

	static function PostSettSet( $post, $data )
	{
		if( !$post )
			return( false );

		$ver = constant( 'seraph_pds' . '\\' . 'PLUGIN_' . strtoupper( $post -> post_type ) . '_SETT_VER' );
		return( PostOptions::Set( $post, $ver, 'Sett', $data, 'seraph_pds' . '\\' ) );
	}

	// #######################################################################

	static function GetRelateRootPath()
	{
		$pluginAbsPath = Gen::ToUnixSlashes( dirname( __FILE__ ) );
		$wpAbsPath = realpath( path_join( $pluginAbsPath, '../../../..' ) );
		return( substr( $pluginAbsPath, strlen( $wpAbsPath ) + 1 ) );
	}

	static function GetAbsoluteRootPath( $path = '' )
	{
		$wpAbsPath = Gen::ToUnixSlashes( realpath( path_join( dirname( __FILE__ ), '../../../..' ) ) );
		if( !$path )
			return( $wpAbsPath );

		$targetAbsPath = path_join( $wpAbsPath, $path );
		$res = realpath( $targetAbsPath );
		return( $res ? $res : $targetAbsPath );
	}

	static function GetRelativeUrl()
	{
		$url = plugins_url( 'seraphinite-post-docx-source' );
		$posScheme = strpos( $url, '://' );
		$posPath = strpos( $url, '/', $posScheme + 3 );
		return( rtrim( substr( $url, $posPath + 1 ), '/' ) );
	}

	static function GetApiUri( $funcName, $args = array() )
	{
		$args = array_merge( array( 'seraph_pds_api' => $funcName ), $args );
		return( add_query_arg( $args, 'index.php' ) );
	}

	// #######################################################################

	static function GetAvailablePlugins( $bActiveOnly = true )
	{
		$res = array();

		$plugins = get_plugins();
		foreach( $plugins as $id => $data )
		{
			if( $bActiveOnly && !is_plugin_active( $id ) )
				continue;

			$a = explode( '/', $id );
			if( is_array( $a ) && count( $a ) )
				$res[] = $a[ 0 ];
		}

		return( $res );
	}

	// #######################################################################

	static function _ActionArg()
	{
		return( 'seraph_pds' . '_act' );
	}

	static function _IsSwitchingActive()
	{
		$switchToArg = 'seraph_pds' . '_switchto';
		return( isset( $_GET[ $switchToArg ] ) );
	}

	static function _SwitchTo( $plgVer )
	{
		require_once( ABSPATH . 'wp-includes/pluggable.php' );

		PluginRmtCfg::Update( true );

		$switchToArg = 'seraph_pds' . '_switchto';
		$_GET[ $switchToArg ] = $plgVer;
		set_site_transient( 'update_plugins', get_site_transient( 'update_plugins' ) );

		$pluginKey = self::_GetTransientUpdatePliginKey();
		wp_redirect( add_query_arg( array( 'action' => 'upgrade-plugin', 'plugin' => $pluginKey, '_wpnonce' => wp_create_nonce( 'upgrade-plugin_' . $pluginKey ), $switchToArg => $plgVer ), admin_url( 'update.php' ) ) );
		//		wp_redirect( add_query_arg( array( 'action' => 'update-selected', 'plugins' => $pluginKey, '_wpnonce' => wp_create_nonce( 'bulk-update-plugins' ), $switchToArg => $plgVer ), admin_url( 'update.php' ) ) );
	}

	static function _RateIt_Set( $mode )
	{
		$state = PluginOptions::Get( self::STATE_VER, 'State', __CLASS__ . '::' );

		if( !$mode )
			$state[ 'rateItRemind' ] = false;
		else
		{
			$rmtCfg = PluginRmtCfg::Get();
			$curTime = intval( time() / 60 );

			$rateItSpanTimeNext = Gen::GetArrField( $rmtCfg, 'Prms.RateItSpanTimeNext', 1440 );
			$state[ 'rateItRemind' ] = $curTime + $rateItSpanTimeNext;
		}

		PluginOptions::Set( self::STATE_VER, 'State', $state, __CLASS__ . '::' );
	}

	static private $_RateIt_ShouldShow = null;

	static function RateIt_ShouldShow()
	{
		if( self::$_RateIt_ShouldShow !== null )
			return( self::$_RateIt_ShouldShow );
		return( self::$_RateIt_ShouldShow = self::__RateIt_ShouldShow() );
	}

	static private function __RateIt_ShouldShow()
	{
		$state = PluginOptions::Get( self::STATE_VER, 'State', __CLASS__ . '::' );

		$mode = @$state[ 'rateItRemind' ];
		if( $mode === false )
			return( false );

		$rmtCfg = PluginRmtCfg::Get();

		$rateItSpanTime = Gen::GetArrField( $rmtCfg, 'Prms.RateItSpanTime', null );
		if( $rateItSpanTime === null )
			return( false );

		if( $mode !== null )
		{
			$curTime = intval( time() / 60 );
			return( $mode < $curTime ? true : 'postponed' );
		}

		$startUseTime = intval( $state[ 'firstUseTimeStamp' ] / 60 );
		$state[ 'rateItRemind' ] = $startUseTime + $rateItSpanTime;
		PluginOptions::Set( self::STATE_VER, 'State', $state, __CLASS__ . '::' );
		return( 'postponed' );
	}

	static private function _RateIt_Check()
	{
		if( self::RateIt_ShouldShow() !== true )
			return( null );

		$res = '';

		$res .= '<strong>Seraphinite Post .DOCX Source</strong>';
		$res .= '<p>' . 'It looks like you\'ve been using the plugin for a while now, thanks! ' . self::GetRateItContent( self::RateItContent_Msg ) . '</p>';

		$res .= '<input style="margin-right:1em;" type="button" class="button-primary" value="' . __( 'Rate it to improve', 'seraph_pds' ) . '" onclick="window.open( \'https://wordpress.org/support/plugin/' . 'seraphinite-post-docx-source' . '/reviews?rate=5#new-post\', \'_blank\' );" />';

		$res .= '<span class="actions">';
		$res .= '<input style="margin-right:1em;" type="button" class="button-link" value="' . __( 'Postpone', 'seraph_pds' ) . '" onclick="seraph_pds_RateIt_Set( true );" />';
		$res .= '<input style="margin-right:1em;" type="button" class="button-link" value="' . __( 'Already rated', 'seraph_pds' ) . '" onclick="seraph_pds_RateIt_Set( false );" />';
		$res .= '</span>';

		$res .= '<span style="visibility:visible; display:none; float: none; margin:0;" class="spinner"></span>';

		$res .=
			'<script>
			function seraph_pds_RateIt_Set( mode )
			{
				jQuery( "#seraph_pds_RateIt_Message .actions" ).hide();
				jQuery( "#seraph_pds_RateIt_Message .spinner" ).show();

				jQuery.ajax(
					{
						url:"' . add_query_arg( array( Plugin::_ActionArg() => '' ), get_admin_url( NULL, 'admin.php' ) ) . '" + "=" + ( mode ? "rateItPostpone" : "rateItDisable" )
					}
				).then(
					function( res )
					{
						jQuery( "#seraph_pds_RateIt_Message .notice-dismiss" ).click();
					},

					function( res )
					{
						jQuery( "#seraph_pds_RateIt_Message .actions" ).show();
						jQuery( "#seraph_pds_RateIt_Message .spinner" ).hide();
					}
				);
			}
			</script>';

		return( Ui::BannerMsg( Ui::MsgInfo, $res, Ui::MsgOptDismissible, 'id="seraph_pds_RateIt_Message"' ) );
	}

	static function _AcceptEula()
	{
		$state = PluginOptions::Get( self::STATE_VER, 'State', __CLASS__ . '::' );
		$state[ 'eulaAcceptedVer' ] = namespace\PLUGIN_EULA_VER;
		PluginOptions::Set( self::STATE_VER, 'State', $state, __CLASS__ . '::' );
	}

	static private function _Eula_Check()
	{
		if( self::IsEulaAccepted() )
			return( NULL );

		$rmtCfg = PluginRmtCfg::Get();

		$acceptBtnName = __( 'Accept the End-User License Agreement', 'seraph_pds' );

		$res = '';
		$res .= '<strong>Seraphinite Post .DOCX Source</strong>';
		$res .= '<p>Please, accept the new ' . Ui::HtmlLink( 'End-User License Agreement', Gen::GetArrField( $rmtCfg, 'Links.UrlEula' ), true ) . '. By pressing "' . $acceptBtnName . '" button you are agreeing with it.</p>';
		$res .= '<input type="button" class="button-primary" value="' . $acceptBtnName . '" style="margin-right: 0.5em;" onclick="' . 'window.location.href=\'' . add_query_arg( array( self::_ActionArg() => 'accept_eula' ), $_SERVER[ 'REQUEST_URI' ] ) . '\'" />';

		return( Ui::BannerMsg( Ui::MsgWarn, $res, Ui::MsgOptDismissible ) );
	}

	static function _OnFilter_AdminFooterText( $text )
	{
		return( '<span id="footer-thankyou">' . self::GetRateItContent() . '</span>' );
	}

	// #######################################################################

	static private function _GetTransientUpdatePliginKey()
	{
		return( 'seraphinite-post-docx-source' . '/' . 'seraphinite-post-docx-source' . '.php' );
	}

	static private function _TransientUpdatePlugins_Set( $value, $plgVer, $switch )
	{
		$dwnldUrl = call_user_func( 'seraph_pds' . '\\__plugin_get_site_transient_update_plugin_url_' . $plgVer );
		if( !$dwnldUrl )
			return( $value );

		$pluginKey = self::_GetTransientUpdatePliginKey();

		if( $switch && !isset( $value -> response[ $pluginKey ] ) && isset( $value -> no_update[ $pluginKey ] ) )
		{
			$value -> response[ $pluginKey ] = $value -> no_update[ $pluginKey ];
			unset( $value -> no_update[ $pluginKey ] );
		}

		if( isset( $value -> response[ $pluginKey ] ) )
			$value -> response[ $pluginKey ] -> package = $dwnldUrl;
		else if( isset( $value -> no_update[ $pluginKey ] ) )
			$value -> no_update[ $pluginKey ] -> package = $dwnldUrl;

		return( $value );
	}

	// #######################################################################

	static function _on_admin_style()
	{
		wp_enqueue_style( 'seraph_pds_style_admincmn', plugins_url( 'AdminUi.Css', __FILE__ ), array(), '1.5.1' );
	}

	static function _on_parse_request( $continue )
	{
		$apiFunc = @$_REQUEST[ 'seraph_pds_api' ];
		if( empty( $apiFunc ) )
			return( $continue );

		unset( $_REQUEST[ 'seraph_pds_api' ] );
		call_user_func( 'seraph_pds\\OnApi_' . $apiFunc, $_REQUEST );
		exit();

		return( false );
	}

	static function _on_check_plugins_updates( $locales )
	{
		$hrUpdated = PluginRmtCfg::Update();

		if( $hrUpdated === Gen::S_OK )
			call_user_func( 'seraph_pds' . '\\__plugin_on_update_remote_data_' . constant( 'seraph_pds' . '_PLUGIN_MODE' ) );
		return( $locales );
	}

	static function _on_site_transient_update_plugins( $value, $transient )
	{
		$plgVer = NULL;
		$switch = false;

		$switchToArg = 'seraph_pds' . '_switchto';
		if( isset( $_GET[ $switchToArg ] ) )
		{
			$plgVer = $_GET[ $switchToArg ];
			$switch = true;
		}
		else
			$plgVer = constant( 'seraph_pds' . '_PLUGIN_MODE' );

		if( !$plgVer )
			return( $value );

		return( self::_TransientUpdatePlugins_Set( $value, $plgVer, $switch ) );
	}

	static function _on_admin_notices()
	{
		{
			$htmlCont = self::_Eula_Check();
			if( $htmlCont )
			{
				echo( $htmlCont );
				// If EULA not accepted stop doing anytning else
				return;
			}
		}

		{
			$htmlCont = self::_RateIt_Check();
			if( $htmlCont )
				echo( $htmlCont );
		}

		call_user_func( 'seraph_pds' . '\\__plugin_on_admin_notices_' . constant( 'seraph_pds' . '_PLUGIN_MODE' ) );
	}

	// #######################################################################

	static function OnOptRead_State( $state, $verFrom )
	{
		if( $verFrom === null )
		{
			$dataEula = PluginOptions::Get( namespace\PLUGIN_EULA_VER, 'Eula', __CLASS__ . '::' );
			$state[ 'eulaAcceptedVer' ] = $dataEula[ 'acceptedVer' ];
			$state[ '_eulaClearPrevStorage' ] = true;
		}

		return( $state );
	}

	static function OnOptWrite_State( $state )
	{
		if( @$state[ '_eulaClearPrevStorage' ] )
		{
			PluginOptions::Del( 'Eula' );
			unset( $state[ '_eulaClearPrevStorage' ] );
		}

		return( $state );
	}

	// Obsolete
	static function OnOptRead_Eula( $data, $verFrom )
	{
		$data[ 'acceptedVer' ] = $verFrom;
		return( $data );
	}
}

// #######################################################################

function __plugin_get_site_transient_update_plugin_url_ext()
{
	return( Gen::GetArrField( PluginRmtCfg::Get(), 'Links.UrlProductDownload' ) );
}

function __plugin_on_update_remote_data_()
{
}

function __plugin_on_admin_notices_()
{
}

// #######################################################################
// #######################################################################
